package ktvcmdserver

import (
	"encoding/binary"
	"fmt"
	"ktvserver/core/udpserver"
	"time"
)

type Route struct {
	Cmd     uint16
	Handler udpserver.Handler
}

var routes = []Route{
	// 系统文件处理函数
	//{0x0024, udpserver.HandlerFunc(handleTest)},
	{CMD_KTVCENTER_ANNOUNCE, udpserver.HandlerFunc(handleNone)},
	// 局域网程序广播版本号
	{CMD_BROADCAST_VERSION, udpserver.HandlerFunc(handleNone)},
	// 对话框数据
	{CMD_DIALOG_DATA, udpserver.HandlerFunc(handleNone)},
	// 询问系统时间是否被修改
	{CMD_CHECK_DATEIME, udpserver.HandlerFunc(handleNone)},

	// 网络配置
	{CMD_QUERY_CONFIG, udpserver.HandlerFunc(KtvQueryConfig)},
	// 查询系统文件大小
	{CMD_GET_KTV_FILE_LEN, udpserver.HandlerFunc(KtvQueryFileLen)},
	// 查询系统文件的HASH值
	{CMD_GET_KTV_FILE_SHA1, udpserver.HandlerFunc(KtvQueryFileSHA1)},

	// 网络下载
	{CMD_PUBLIC_LOGIN, udpserver.HandlerFunc(KtvPublicUserLogin)},
	{CMD_PUBLIC_HEARTBEAT, udpserver.HandlerFunc(KtvPublicUserHeartbeat)},
	{CMD_PUBLIC_USER_STANDBY, udpserver.HandlerFunc(KtvPublicUserStandby)},
	{CMD_PUBLIC_RELOAD_BLACK_LIST, udpserver.HandlerFunc(KtvPublicReloadBlackList)},
}

func handleTest(w udpserver.ResponseWriter, req *udpserver.Request) {
	fmt.Printf("handleTest")
	fmt.Printf("%x", req.Srv.RecvBuffer)
}

// 什么都不做
func handleNone(w udpserver.ResponseWriter, req *udpserver.Request) {
	//fmt.Printf("handleNone")
}

// 处理函数示例
func handleNotFound(w udpserver.ResponseWriter, req *udpserver.Request) {
	fmt.Printf("Udpserver handleNotFound, ")

	if req.CmdMessage.IsOK() {
		fmt.Printf("Cmd=0x%x, Len=%d, Addr=%v\n", req.CmdMessage.Cmd, req.Rd.Len(), req.RemoteAddr)
	} else {
		fmt.Printf("Unknown, Len=%d, Addr=%v\n", req.Rd.Len(), req.RemoteAddr)
	}

	daytime := time.Now().Unix()
	//fmt.Println(req.Rd.Len(), req.RemoteAddr)
	b := make([]byte, 4)
	binary.BigEndian.PutUint32(b, uint32(daytime))

	w.Write(b)
	//w.WriteString("aaaabbbb")

}

// 获取服务器的命令代码处理函数映射
func GetServerMux() *udpserver.ServeMux {

	myMux := udpserver.NewServeMux()

	for i := 0; i < len(routes); i++ {
		myMux.Handle(routes[i].Cmd, routes[i].Handler)
	}

	// 注册notfound
	myMux.HandleNotFound(udpserver.HandlerFunc(handleNotFound))

	return myMux
}
